package com.yangrd.airship.sys.web;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.yangrd.airship.upms.domain.User;
import com.yangrd.airship.upms.domain.UserRepository;
import com.yangrd.airship.upms.domain.UserSpec;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

/**
 * @author yangrd
 * @date 2021/11/26
 */
@RequiredArgsConstructor

@RestController
@RequestMapping("/auth")
public class AuthController {

    private final UserRepository userRepository;

    @GetMapping("/login")
    public String login(String username,String password){
        Optional<User> optionalUser = userRepository.findOne(UserSpec.toSpec(username));
        String pwd = optionalUser.map(User::getPassword).orElseThrow(() -> new IllegalArgumentException("用户密码不正确"));
        if(pwd.equals(password)){
            StpUtil.login(optionalUser.get().getId(),"pc");
            return StpUtil.getTokenValue();
        }else {
            throw new RuntimeException("用户密码不正确");
        }
    }

    @SaCheckLogin
    @GetMapping("/logout")
    public void logout(){
        StpUtil.logout();
    }


    @GetMapping("/token")
    public SaTokenInfo token(){
        return StpUtil.getTokenInfo();
    }

    @SaCheckLogin
    @GetMapping("/me")
    public User me(){
       return userRepository.findById(Integer.valueOf(StpUtil.getLoginId().toString())).orElseThrow(RuntimeException::new);
    }
}
